package com.example.sherlockzhong.plush_v2.Subscriptions;

/*
 * Created by DosonLeung 2014/8/24.
 */

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.sherlockzhong.plush_v2.CardBeans.AddOrgBean;
import com.example.sherlockzhong.plush_v2.CardIni.AddOrganizationIni;
import com.example.sherlockzhong.plush_v2.Components.adapter.OrgListAdapter;
import com.example.sherlockzhong.plush_v2.Components.buttons.BackButton;
import com.example.sherlockzhong.plush_v2.Models.PushModel;
import com.example.sherlockzhong.plush_v2.R;
import com.example.sherlockzhong.plush_v2.Utils.NetworkUtils;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;

import java.util.HashMap;

public class AddOrganizationActivity extends Activity {
    AddOrgBean aob = new AddOrgBean();
    JSONArray allPosterArray;
    public Thread load = new Thread() {
        @Override
        public void run() {
        allPosterArray = PushModel.listAllPosters("1");
        handler.sendEmptyMessage(0x123);
        }
    };
    JSONArray subscribedArray;
    public Thread refreshLocal = new Thread() {
        @Override
        public void run() {
            subscribedArray = PushModel.listSubscribedPosters();
            handler.sendEmptyMessage(0x200);
        }
    };
    OrgListAdapter OLA;
    Handler handler = new Handler() {
        /**
         * 0x123 第一次进入刷新
         * 0x200 刷新后再刷新本地的标志
         * 0x401 刷新本地成功
         * */
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x123) {
                stopReflashDialog();
                if(!animation) {
                    Toast.makeText(AddOrganizationActivity.this, "关注成功！", Toast.LENGTH_SHORT).show();
                    animation = true;
                }
                if (allPosterArray != null) {
                    OLA = AddOrganizationIni.init(AddOrganizationActivity.this, handler, allPosterArray, aob);
                }
            } else if (msg.what == 0x200) {
                refreshLocal = newrefreshhread(refreshLocal);
                refreshLocal.start();
            } else if (msg.what == 0x401) {
                stopReflashDialog();
                Toast.makeText(AddOrganizationActivity.this, "没有新的社团", Toast.LENGTH_SHORT).show();
            } else if (msg.what == 0x202) {
                if (OLA != null) {
                    int lastIndex = OLA.getBitmapList().size() - 1;
                    int length = OLA.getImageList().size();
                    HashMap<String, Object> item = null;
                    if (length > lastIndex) {
                        if (OLA.getBitmapList().size() >= lastIndex + 1) {
                            try {
                                item = OLA.getBitmapList().get(lastIndex);
                            } catch (ArrayIndexOutOfBoundsException e) {
                                e.printStackTrace();
                            }
                            if (item != null) {
                                OLA.getBitmapList().get(lastIndex);
                                Integer index = (Integer) item.get("index");
                                Bitmap bitmap = (Bitmap) item.get("bitmap");
                                ImageView img = (ImageView) item.get("image");
                                //Log.e("来图片了......", "v = " + OLA.getImageList().get(index) + " name = " + img + " index = " + index + "  lastIndex = " + lastIndex);
                            /*
                            for (int i = 0; i < length; i++) {
                                if (img == OLA.getImageList().get(i)) {
                                    img.setImageBitmap(bitmap);
                                }
                            }*/
                                (OLA.getImageList().get(index)).setImageBitmap(bitmap);
                            }
                        }
                    }
                }
            }
        }
    };
    private ProgressDialog pd;
    public ImageView refresh;
    //true表示需要动画,false表示不需动画
    public boolean animation = true;
    //跟新
    public Thread newLoadThread(Thread load) {
        load = new Thread() {
            @Override
            public void run() {
                allPosterArray = PushModel.listAllPosters("1");
                if (allPosterArray != null)
                    handler.sendEmptyMessage(0x200);
                else
                    handler.sendEmptyMessage(0x401);
            }
        };
        return load;
    }

    //跟新刷新线程
    public Thread newrefreshhread(Thread refresh) {
        refresh = new Thread() {
            @Override
            public void run() {
                subscribedArray = PushModel.listSubscribedPosters();
                handler.sendEmptyMessage(0x123);
            }
        };
        return refresh;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_organization_list);
        BackButton AOB = (BackButton) findViewById(R.id.addorg_back);
        refresh = (ImageView) findViewById(R.id.add_org_refresh);
        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            AddOrganizationIni.refreshEvent(refresh, AddOrganizationActivity.this,true);
            }
        });
        AOB.setApp(this);
        if (NetworkUtils.getAvailableNetWorkInfo(this) != null) {
            showReflashDialog("加载中...");
            load.start();
        } else {
            Toast.makeText(this, "刷新失败,请检查网络设置。", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    /**
     * 显示刷新的时候的等待进度条
     */
    public void showReflashDialog(String msg) {
        this.pd = new ProgressDialog(this);
        this.pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        this.pd.setCancelable(true);
        this.pd.setMessage(msg);
        this.pd.show();
    }

    /**
     * 结束刷新的时候的等待进度条
     */
    public void stopReflashDialog() {
        if (this.pd != null) {
            pd.dismiss();
        }
    }

    public void onDestory() {
        super.onDestroy();
        stopReflashDialog();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            stopReflashDialog();
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }



}
